package cn.lin.service.impl;

import cn.lin.domain.Catalog;
import cn.lin.domain.FilePhoto;
import cn.lin.mapper.FileMapper;
import cn.lin.service.FileService;
import cn.lin.util.FileUtil;
import cn.lin.util.OSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cn.Lin
 * @create 2024-12-03-14:41
 */
@Service
@Transactional
public class FileServiceImpl implements FileService {

    @Autowired
    private FileMapper fileMapper;

    @Override
    public List<String> findFilePhotoPathById(Integer id) {
        return fileMapper.findFilePhotoPathById(id);
    }

    @Override
    public boolean addFilePhotoPath(MultipartFile file, int pid, int classId) {

        String fileName = file.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf(".")+1);
        System.out.println(ext);// doc,docx,pdf,ppt,pptx
        try {
            //将文件上传到远端
            String filePath = OSSUtil.upload(fileName,file.getInputStream());

            //封装catalog对象用来存入catalog表
            Catalog catalog = new Catalog();
            catalog.setPid(pid);
            catalog.setLevel(3);
            catalog.setClassId(classId);
            catalog.setModelName(fileName);
            catalog.setFileName(filePath);

            //存入catalog表
            int zoe = fileMapper.addLevel3(catalog);
            if(zoe != 1){
                return false;
            }

            //查询刚刚存入那条数据的id
            int catalogId = fileMapper.findIdByPath(filePath);

            //将文件分割为图片
            List<String> urls = FileUtil.file2Png(filePath,ext);
            if(urls.isEmpty()){
                return false;
            }

            //封装filePhoto对象集合
            List<FilePhoto> filePhotos = new ArrayList<>();
            for (String url : urls) {
                FilePhoto filePhoto = new FilePhoto();
                filePhoto.setCatalogId(catalogId);
                filePhoto.setPhotoUrl(url);
                filePhotos.add(filePhoto);
            }

            //将数据存入file_photo表中
            int ret = fileMapper.addFilePhotoPath(filePhotos);

            //当影响行数等于图片的数量时返回true
            return ret == urls.size();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
